"""
用户相关功能
"""
from django.shortcuts import render,HttpResponse,HttpResponseRedirect
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from django.http import JsonResponse
from app.forms import account
from app import models
from utils import captcha
from django.db.models import Q
import uuid
import datetime

# Create your views here.

def register(request):
    if request.method == 'GET':
        form = account.RegisterModelForm()
        return render(request, 'app/register.html', {'form': form})
    else:
        form = account.RegisterModelForm(data=request.POST)
        if form.is_valid():
            # 验证通过，写入数据库（密码要是密文）
            # instance = form.save，在数据库中新增一条数据，并将新增的这条数据赋值给instance
            # 用户表中新建一条数据（注册）
            instance = form.save()
            policy_obj = models.PricePolicy.objects.filter(category=1,title='个人免费版').first()
            models.Transaction.objects.create(
                status=2,
                order=str(uuid.uuid4()),
                user=instance,
                price_policy=policy_obj,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now(),
            )
            return JsonResponse({'status': True, 'data': 'api/v1/login/sms/'})
        return JsonResponse({'status': False, 'error': form.errors})

def send_sms(request):
    if request.method == 'POST':
        form = account.SendSmsForm(request,data=request.POST)
        if form.is_valid():
            return JsonResponse({'status': True},safe=False)
        return JsonResponse({'status': False, 'error': form.errors},safe=False)

def login_sms(request):
    if request.method == 'GET':
        form = account.LoginSmsForm()
        return render(request,'app/login_sms.html',{'form':form})
    else:
        form = account.LoginSmsForm(request.POST)
        if form.is_valid():
            user_obj = form.cleaned_data['phone']

            return JsonResponse({'status':True,'data':'/index/'})
        return JsonResponse({"status":False,'error':form.errors})


def login(request):
    if request.method == 'GET':
        form = account.LoginForm(request)
        return render(request,'app/login.html',{'form':form})
    else:
        form = account.LoginForm(request,data=request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user_obj = models.User.objects.filter(Q(email=username)|Q(phone=username))\
                .filter(password=password).first()
            if user_obj:
                # 登录成功为止1
                request.session['user_id'] = user_obj.id
                request.session.set_expiry(60 * 60 * 24 * 14)
                return HttpResponseRedirect('/api/v1/index/')
            if not user_obj:
                form.add_error('username','用户名或密码错误')
        return render(request,'app/login.html',{'form':form})


def login_code(request):
    if request.method == 'GET':

        image_obj, code = captcha.check_code()
        from io import BytesIO
        stream = BytesIO()
        image_obj.save(stream, 'png')
        request.session['login_code'] = code
        request.session.set_expiry(60)
        return HttpResponse(stream.getvalue())

def logout(request):
    if request.method == 'GET':
        request.session.flush()   #清空当前用户session
        return HttpResponseRedirect('app:login')


class index(APIView):
    versioning_class = URLPathVersioning
    def get(self,request):
        self.dispatch
        data = {
            'msg':'OK'
        }
        return Response(data)

